import {
  Box,
  Button,
  Card,
  Heading,
  ListItem,
  OrderedList,
  Stack,
  useMediaQuery,
  Flex,
  CardFooter,
} from '@chakra-ui/react';
import React, { useRef } from 'react';
import QRCode from 'qrcode.react';
import { Link } from 'react-router-dom';
import { useAppSelector } from '../../redux/hooks';
import useSocket from '../hooks/useSocket';

export default function LinkPage(): JSX.Element {
  const [isLargerThanPhone] = useMediaQuery('(min-width: 800px)');

  const players = useAppSelector((store) => store.game.players);
  const roomName = useAppSelector((store) => store.game.roomName);
  const { startHandler } = useSocket();
  const linkRef = useRef<HTMLAnchorElement>(null);

  const copyLinkToClipboard = (): void => {
    if (linkRef.current) {
      navigator.clipboard
        .writeText(linkRef.current.href)
        .then(() => {
          alert('Ссылка скопирована в буфер обмена');
        })
        .catch((error) => {
          console.error('Ошибка при копировании ссылки:', error);
        });
    }
  };

  const mainContainerStyle: React.CSSProperties = {
    backgroundImage: isLargerThanPhone
      ? 'url(/img/linkWeb.png)'
      : 'url(/img/linkMob.png)',
    backgroundSize: 'cover',
    backgroundRepeat: 'no-repeat',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    height: '100vh',
  };

  return (
    <Box as="form" style={mainContainerStyle}>
      <Flex justifyContent="center" marginBottom="10px">
        <Card
          overflow="hidden"
          variant="outline"
          style={{
            backgroundImage: 'url(/img/p.png)',
            backgroundSize: 'cover',
            backgroundRepeat: 'no-repeat',
            marginRight: isLargerThanPhone ? '30px' : '10px',
            width: isLargerThanPhone ? '300px' : '200px',
            justifyContent: 'center',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
          }}
        >
          <QRCode
            value={`https://${import.meta.env.VITE_CUR_DOMAIN}/loading/${roomName}`}
            size={isLargerThanPhone ? 200 : 140}
          />
          <CardFooter marginTop="10px" alignItems="center">
            <Link
              to={`https://${import.meta.env.VITE_CUR_DOMAIN}/loading/${roomName}`}
              ref={linkRef}
              style={{ fontSize: isLargerThanPhone ? '27px' : '18px' }}
            >
              Подключиться к квизу по ссылке:
            </Link>
            <Button
              onClick={copyLinkToClipboard}
              style={{ border: '2px solid grey', fontSize: isLargerThanPhone ? '17px' : '14px' }}
            >
              Скопировать
            </Button>
          </CardFooter>
        </Card>

        <Card
          borderWidth="1px"
          overflow="hidden"
          variant="outline"
          width={isLargerThanPhone ? '300px' : '200px'}
          height="400px"
          fontSize="25px"
          style={{
            backgroundImage: 'url(/img/p.png)',
            backgroundSize: 'cover',
            backgroundRepeat: 'no-repeat',
          }}
        >
          <Stack spacing="4" fontSize={isLargerThanPhone ? '50px' : '14px'}>
            <OrderedList>
              {players.map((player) => (
                <ListItem key={player.id}>{player.name}</ListItem>
              ))}
            </OrderedList>
          </Stack>
        </Card>
      </Flex>
      <Button
        variant="solid"
        colorScheme="yellow"
        size="lg"
        minW={isLargerThanPhone ? '620px' : '410px'}
        onClick={() => startHandler(roomName)}
        marginBottom="20px"
        fontSize={isLargerThanPhone ? '28px' : '14px'}
      >
        Start
      </Button>
    </Box>
  );
}
